import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import store from './store'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/forgetPassword'] // 免登录白名单

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (store.getters.userInfo != null) {
    // 如果已登录
    if (to.path === '/login') {
      // 跳过登录
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 没有登录
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      if (to.path === '/404') {
        next()
      } else {
        next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      }
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})